<script lang="ts">
	import { PageLoading } from '$components/basic/loading';
	import { getContext, onMount } from 'svelte';
	import PosUnit from './PosUnit.svelte';
	import { alova } from '$utils/request';
	import { page } from '$app/stores';
	import Button from '@smui/button';
	import { SubTrackStatusMapper, TrackStatusMapper } from './constant';
	import { handleReqMounted } from '@/hooks/handleReq';
	import type { I18nExport } from '@/i18n';
	import { getValue } from '$utils/get';
	import { createMessage } from '$components/basic/message';
	import { formatDate } from '$utils/date';
	import { goBack, goto } from '$utils/intercept';
	import Picture from '$components/basic/picture/picture.svelte';
	import Dialog from '$components/basic/dialog/Dialog.svelte';

	let open = false; // 是否显示图片
	let dialogRef: any = null;
	let viewUrl = ''; // 图片地址

	const openPictureViewer = (src: string) => {
		if (src.includes('.pdf')) {
			return window.open(src, '_blank');
		}
		viewUrl = src;
		open = true;
	};

	const getParams = () =>
		$page.url.search
			.split('?')[1]
			.split('&')
			.reduce((pre, cur) => {
				return { ...pre, [cur.split('=')[0]]: cur.split('=')[1] };
			}, {});

	let info: IObject[] = [];
	let data: IObject | null = null;
	$: len = info.length;

	const setTrackInfo = (res: IObject) => {
		data = res;
		info = (res.origin_info?.trackinfo || []).map((item: any, index: number) => {
			const { checkpoint_date: date, checkpoint_delivery_status: status } = item;
			const { location, checkpoint_delivery_substatus: substatus, tracking_detail: detail } = item;
			const type =
				index === 0
					? status === 'delivered'
						? 'success'
						: ['undelivered', 'notfound'].includes(status)
							? 'danger'
							: 'primary'
					: 'success';
			const hollow = type === 'primary' ? true : false;
			return { location, status, substatus, date, type, detail, hollow };
		});
	};

	const params: Partial<{ orderId: string; shipNumber: string }> = getParams();
	const getUrl = () =>
		`/order/track?${Object.entries(params)
			.map(([k, v]) => `${k}=${v}`)
			.join('&')}`;
	const handle = (res) => setTrackInfo(res.data?.[0]);
	const { loading: loadingTrack, reqInfo: getTrackInfo } = handleReqMounted(getUrl, {
		type: 'get',
		handle,
		isInit: false
	});

	let detail: Partial<Order.Order> = {};
	const cacheFor = 0;
	const { loading: loadingDetail, reqInfo: getOrderDetail } = handleReqMounted(
		() => '/order/detail?id=' + params.orderId,
		{
			type: 'get',
			params: { cacheFor },
			isInit: false,
			handle: (res) => (detail = res.data)
		}
	);

	$: loading = $loadingTrack && $loadingDetail;

	onMount(() => {
		if (params.shipNumber) {
			getTrackInfo();
		} else {
			getOrderDetail();
		}
	});

	const { t } = getContext<I18nExport>('lan');

	const copyText = (text) => {
		navigator.clipboard.writeText(text as string);
		createMessage({ type: 'success', message: 'Copied!', duration: 2000 });
	};

	function formatValue(name: string, item: string) {
		if (name === 'Created') {
			const v = getValue(data, item, '--').substring(0, 10);
			const date = new Date(v);
			return formatDate('MM/DD/YY', date);
		}

		return getValue(data, item, '--');
	}
</script>

<div class="w-full flex-cc">
	<div class="w-1320px max-w-100% min-w-350px flex flex-col py-40px">
		<div class="w-full flex justify-between items-center bg-gray-2 h-48px mb-20px pr-20px">
			<Button class="gap-10px h-full" style="--mdc-theme-primary: #6b7280" on:click={goBack}>
				<span class="material-symbols-outlined"> undo </span>
				<span>Back</span>
			</Button>
			{#if data}
				{@const list = ['courier_code', 'original', 'destination', 'weight', 'created_at']}
				{@const names = ['Courier', 'From', 'To', 'Weight', 'Created']}
				<div class="flex-cc gap-40px h-full">
					<span class="color-blue-5 font-size-16px">
						ShipNumber:
						<button
							class="color-blue-5 font-size-15px border-none outline-none inline p-0 m-0 bg-transparent cursor-pointer"
							on:click={() => copyText(getValue(data, 'tracking_number', '--'))}
						>
							{getValue(data, 'tracking_number', '--')}
						</button>
					</span>
					<!--点击可复制 -->
					{#each list as item, index (item)}
						<span class="span-border relative color-gray-5 font-size-16px">
							{names[index]}:
							<span class="font-size-15px">{formatValue(names[index], item)}</span>
						</span>
					{/each}
				</div>
			{/if}
			{#if detail.express && detail.express.file}
				<div class="h-full flex-cc gap-10px">
					<span class="color-blue-7">S/O:# {detail.orderno}</span>
					<Button variant="raised" on:click={() => goto('/order/detail?id=' + params.orderId)}>
						view
					</Button>
					<Button
						variant="raised"
						style="--mdc-theme-primary: #ef4444"
						on:click={() => goto('/order/invoice?id=' + params.orderId)}
					>
						invoice
					</Button>
				</div>
			{/if}
		</div>

		<div class="px-10px">
			<PageLoading bind:loading>
				{#each info as item, index}
					<PosUnit
						position={index === 0 ? 'start' : index === len - 1 ? 'end' : 'middle'}
						text={`${item.location ? '【' + item.location + '】' : ''} ${$t(SubTrackStatusMapper[item.substatus]) || $t(TrackStatusMapper[item.status]) || '--未知--'} ${item.detail}`}
						date={item.date}
					/>
				{/each}
				{#if detail.express && detail.express.file}
					<div class="w-full grid grid-cols-3 gap-10px">
						{#each detail.express.file as item, index}
							<button
								on:click={() => openPictureViewer(item.url)}
								class="m-0 border-none! outline-none! bg-gray-1 flex flex-row h-210px p-5px rounded-8px gap-5px shadow-xl hover:shadow-2xl hover:shadow-bluegray transition-all duration-300 cursor-pointer"
							>
								{#if item.name.includes('.pdf')}
									<div
										class="min-w-200px w-200px h-200px flex-cc rounded-8px! border border-solid border-gray-1 overflow-hidden"
										style="text-decoration: none"
									>
										<span
											class="material-symbols-outlined color-red-6 font-size-180px! whitespace-pre-wrap"
										>
											picture_as_pdf
										</span>
									</div>
									<span class="whitespace-pre-wrap break-words pt-15px color-gray-4 flex-1"
										>{item.name}</span
									>
								{:else}
									<Picture
										class="min-w-200px w-200px h-200px rounded-8px! border border-solid border-gray-1 overflow-hidden"
										src={item.url}
										alt={item.name}
									/>

									<span class="whitespace-pre-wrap break-words pt-15px color-gray-4 flex-1">
										{item.name}
									</span>
								{/if}
							</button>
						{/each}
					</div>
				{/if}
			</PageLoading>
			<Dialog bind:open bind:this={dialogRef} title="Picture viewer">
				<img class="w-full h-auto" src={viewUrl} alt="viewUrl" />
			</Dialog>
		</div>
	</div>
</div>

<style>
	.span-border::before {
		content: '';
		position: absolute;
		top: 50%;
		left: -20px;
		width: 0.5px;
		height: 1em;
		z-index: inherit;
		transform: translate(-50%, -50%);
		box-shadow: none;
		background-image: none !important;
		background-color: #aaa;
	}
</style>
